package org.example.trigger.http;


import com.alibaba.nacos.api.config.annotation.NacosValue;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.example.api.IUserRaffleApiService;
import org.example.api.model.dto.RafflePrizeDTO;
import org.example.api.model.response.Response;
import org.example.domain.user_raffle.model.entity.PrizeEntity;
import org.example.domain.user_raffle.service.IUserRaffleService;
import org.example.types.annotation.RateLimit;
import org.example.types.common.ResponseCode;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author lxc18
 * @date 2025/3/30 18:22
 * @description UserRaffleController
 */
@RestController
@Slf4j
@RequestMapping("/api/${app.config.api-version}/user-raffle/")
@Tag(name = "用户抽奖")
public class UserRaffleController implements IUserRaffleApiService {
    @Resource
    private IUserRaffleService userRaffleService;

    @NacosValue(value = "${down:true}", autoRefreshed = true)
    private boolean downgrade;

    @Override
    @RequestMapping(value = "raffle", method = RequestMethod.GET)
    @Operation(summary = "用户抽奖", description = "输入用户id，活动id，进行抽奖")
    @RateLimit(limit = 5,windowSize = 1) // 每秒最大请求数

    public Response<RafflePrizeDTO> doRaffle(Long userId, Long activityId) {
        //降级
        if(downgrade){
            log.info("用户{}在活动{}抽奖，降级", userId, activityId);
            return Response.<RafflePrizeDTO>builder()
                   .code(ResponseCode.API_DOWNGRADE.getCode())
                   .info(ResponseCode.API_DOWNGRADE.getInfo())
                   .data(null)
                   .build();
        }
        //1、验证活动是否有效
        if (!userRaffleService.isActivityValid(activityId)) {
            log.error("活动{}无效", activityId);
            return Response.<RafflePrizeDTO>builder()
                    .code(ResponseCode.USER_RAFFLE_ACTIVITY_INVALID.getCode())
                    .info(ResponseCode.USER_RAFFLE_ACTIVITY_INVALID.getInfo())
                   .data(null)
                   .build();
        }
        //2、验证用户额度是否大于0,用户额度扣减、已用额度增加
        log.info("用户{}在活动{}抽奖，用户额度扣减、已用额度增加", userId, activityId);
        int usedQuota = userRaffleService.deductUserQuotaAndAddUsedQuota(activityId, userId);
        if (usedQuota==-1) {
            log.error("用户{}在活动{}的额度不足", userId, activityId);
            return Response.<RafflePrizeDTO>builder()
                   .code(ResponseCode.USER_RAFFLE_QUOTA_NOT_ENOUGH.getCode())
                  .info(ResponseCode.USER_RAFFLE_QUOTA_NOT_ENOUGH.getInfo())
                  .data(null)
                  .build();
        }
        //3、参与抽奖：
        Long prizeId = userRaffleService.participateInRaffle(activityId, userId,usedQuota);
        log.info("用户{}在活动{}抽奖，奖品id为{}", userId, activityId, prizeId);
        //4、根据抽奖的返回值，进行后续操作
        //是否是保底奖品
//        if (userRaffleService.isGuaranteePrize(activityId,prizeId)) {
//            //对已用额度清空
//            userRaffleService.clearUsedQuota(activityId, userId);
//            log.info("用户{}在活动{}抽奖，是保底奖品,已用额度清空", userId, activityId);
//        }

        //5、用户抽奖记录增加
        userRaffleService.addUserRaffleRecord(activityId, userId, prizeId);
        log.info("用户{}在活动{}抽奖，用户抽奖记录增加", userId, activityId);
        //6、返回结果

        if (prizeId != null) {
            //发奖
            //TODO:发奖
            //查询奖品信息
            PrizeEntity prizeEntity = userRaffleService.queryPrizeById(prizeId);
            RafflePrizeDTO rafflePrizeDTO = RafflePrizeDTO.builder()
                        .prizeName(prizeEntity.getPrizeName())
                        .prizeDescription(prizeEntity.getPrizeDescription())
                        .prizeType(prizeEntity.getPrizeType())
                        .build();
            return Response.<RafflePrizeDTO>builder()
                   .code(ResponseCode.SUCCESS.getCode())
                   .info(ResponseCode.SUCCESS.getInfo())
                   .data(rafflePrizeDTO)
                   .build();
        }
        else {

            return Response.<RafflePrizeDTO>builder()
                  .code(ResponseCode.USER_RAFFLE_NO_PRIZE.getCode())
                  .info(ResponseCode.USER_RAFFLE_NO_PRIZE.getInfo())
                  .data(null)
                  .build();
        }
    }
}
